<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'vke:teacherUser:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }}</span>
    </template>
    <BasicForm @register="registerForm">
      <template #userRoleString>
        <BasicTable @register="registerUserRoleTable" />
      </template>
      <template #headPortrait="{ record: childRecord }">
        <!-- <BasicUpload
          v-model:value="childRecord.dataMap"
          :bizKey="childRecord.id"
          :bizType="'teacherUser_avatar'"
          :uploadType="'image'"
          :loadTime="record.__t"
          @onchange="changePortrait"
        /> -->
        <Upload
          accept=".jpg, .jpeg, .png"
          :file-list="fileList"
          :remove="handleRemove"
          :before-upload="beforeUpload"
        >
          <a-button> <Icon icon="ant-design:upload-outlined" /> {{ t('选择文件') }} </a-button>
          <!-- <span class="ml-4">{{ uploadInfo }}</span> -->
        </Upload>
      </template>
    </BasicForm>
    <!-- <CropperAvatar
        style="margin-left: 140px;"
        :value="avatar"
        btnText="更换头像"
        :btnProps="{ preIcon: 'ant-design:cloud-upload-outlined' }"
        @change="updateAvatar"
         width="150"
          /> -->
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsVkeTeacherUserForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { CropperAvatar } from '/@/components/Cropper';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    TeacherUser,
    checkEmpNo,
    teacherUserSave,
    teacherUserForm,
  } from '/@/api/vke/teacherUser';
  import { checkLoginCode } from '/@/api/sys/user';
  // import { UploadOutlined } from '@ant-design/icons-vue';
  import { Upload } from 'ant-design-vue';
  import { roleTreeData } from '/@/api/sys/role';
  import { BasicTable, useTable } from '/@/components/Table';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('vke.teacherUser');
  const { showMessage } = useMessage();
  const record = ref<TeacherUser>({} as TeacherUser);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增教师') : t('编辑教师'),
  }));
  const ctrlPermi = ref<String>('');
  const op = ref<String>('');
  const avatar = ref('');
  const fileList = ref([]);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('登录账号'),
      field: 'loginCode',
      component: 'Input',
      componentProps: {
        maxlength: 20,
      },
      rules: [
        { required: true },
        { min: 4, max: 20, message: t('请输入长度在 4 到 20 个字符之间') },
        { pattern: /^[\u0391-\uFFE5\w]+$/, message: t('不能输入特殊字符') },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              if (!value || value === '') return resolve();
              checkLoginCode(record.value.loginCode || '', value)
                .then((res) => (res ? resolve() : reject(t('登录账号已存在'))))
                .catch((err) => reject(err.message || t('验证失败')));
            });
          },
        },
      ],
    },
    {
      label: t('工号'),
      field: 'vteacher.jobNumber',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      rules: [
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              if (!value || value === '') return resolve();
              checkEmpNo(record.value.employee?.empNo || '', value)
                .then((res) => (res ? resolve() : reject(t('员工工号已存在'))))
                .catch((err) => reject(err.message || t('验证失败')));
            });
          },
        },
      ],
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('姓名'),
      field: 'vteacher.teacherName',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      required: true,
      ifShow: () => op.value === 'add' || op.value === 'edit' || op.value === 'auth',
    },
    // {
    //   label: t('电子邮箱'),
    //   field: 'email',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 300,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    //   rules: [{ type: 'email', message: t('请填写正确的邮箱地址') }],
    // },
    // {
    //   label: t('手机号码'),
    //   field: 'mobile',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    {
      label: t('教师类型'),
      field: 'vteacher.teacherType',
      component: 'RadioGroup',
      // defaultValue: '1',
      componentProps: {
        dictType: '	vke_teacher_type',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    // {
    //   label: t('权重'),
    //   field: 'userWeight',
    //   helpMessage: '排序，权重越大排名越靠前，请填写数字。',
    //   component: 'InputNumber',
    //   defaultValue: 0,
    //   componentProps: {
    //     maxlength: 8,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },

    {
      label: t('详细信息'),
      field: 'employeeInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },

    // {
    //   label: t('员工工号'),
    //   field: 'employee.empNo',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 32,
    //   },
    //   rules: [
    //     { required: false },
    //     {
    //       validator(_rule, value) {
    //         return new Promise((resolve, reject) => {
    //           if (!value || value === '') return resolve();
    //           checkEmpNo(record.value.employee?.empNo || '', value)
    //             .then((res) => (res ? resolve() : reject(t('员工工号已存在'))))
    //             .catch((err) => reject(err.message || t('验证失败')));
    //         });
    //       },
    //     },
    //   ],
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    {
      label: t('出生年月'),
      field: 'vteacher.dateBirth',
      component: 'DatePicker',
      componentProps: {
        dictType: 'sys_user_sex',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    // {
    //   label: t('性别'),
    //   field: 'vteacher.dateBirth',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 32,
    //   },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },
    {
      label: t('性别'),
      field: 'vteacher.sex',
      component: 'RadioGroup',
      // defaultValue: '1',
      componentProps: {
        dictType: 'sys_user_sex',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('职称'),
      field: 'userType',
      component: 'Select',
      componentProps: {
        dictType: 'sys_user_type',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('代课科目'),
      field: 'vteacher.substituteSubjects',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('是否班主任'),
      field: 'vteacher.isHeadmaster',
      component: 'RadioGroup',
      // defaultValue: '1',
      componentProps: {
        dictType: '	sys_yes_no',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('代课年级'),
      field: 'vteacher.substituteGrade',
      component: 'Select',
      componentProps: {
        dictType: 'vke_grade',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('代课班级'),
      field: 'vteacher.substituteClass',
      component: 'Select',
      componentProps: {
        dictType: 'vke_class',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('头像'),
      field: 'vteacher.headPortrait',
      component: 'Uploads',
      componentProps: {
        multiple: false,
        maxNumber: 1,
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'teacherUser_avatar',
        uploadType: 'image',
        onChange: (e: ChangeEvent) => {
          console.log(e);
          avatar.value = e;
        },
        // slots: { customRender: 'headPortrait' },
      },
      ifShow: () => {
        return op.value === 'add' || op.value === 'edit';
      },
      colProps: { lg: 24, md: 24 },
    },
    // {
    //   label: t('头像'),
    //   field: 'vteacher.headPortrait',
    //   component: 'Input',
    //   // componentProps: {
    //   //   // loadTime: computed(() => record.value.__t),
    //   //   // bizKey: computed(() => record.value.id),
    //   //   bizType: 'testData_image',
    //   //   uploadType: 'image',
    //   // },
    //   slot: 'headPortrait',
    //   colProps: { lg: 24, md: 24 },
    // },
    // {
    //   label: t('备注信息'),
    //   field: 'remarks',
    //   component: 'InputTextArea',
    //   componentProps: {
    //     maxlength: 500,
    //   },
    //   colProps: { lg: 24, md: 24 },
    //   ifShow: () => op.value === 'add' || op.value === 'edit',
    // },

    {
      label: t('角色信息'),
      field: 'roleInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: () => op.value === 'add' || op.value === 'auth',
    },
    {
      label: t('分配角色'),
      field: 'userRoleString',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'userRoleString',
      show: () => op.value === 'add' || op.value === 'auth',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
    labelWidth: 120,
  });
  const handleChange = (info: UploadChangeParam) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      // message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      // message.error(`${info.file.name} file upload failed.`);
    }
  };

  const [registerUserRoleTable, userRoleTable] = useTable({
    columns: [
      {
        title: t('角色名称'),
        dataIndex: 'name',
        width: 260,
        align: 'center',
      },
      {
        title: t('角色编码'),
        dataIndex: 'id',
        width: 260,
        align: 'center',
      },
    ],
    rowSelection: { type: 'checkbox' },
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setUserRoleTableData(res: Recordable) {
    const dataSource = await roleTreeData({
      userType: 'teacher',
      ctrlPermi: ctrlPermi.value,
    });
    userRoleTable.setTableData(dataSource || []);
    userRoleTable.setSelectedRowKeys(res.roleList?.map((item) => item.id) || []);
  }
  function changePortrait(e) {
    console.log(e);
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    userRoleTable.setTableData([]);
    userRoleTable.setSelectedRowKeys([]);
    setDrawerProps({ loading: true });
    op.value = data.op || 'add';
    const res = await teacherUserForm(data);
    record.value = (res.teacherUser || {}) as TeacherUser;
    ctrlPermi.value = res.ctrlPermi || '2';
    setFieldsValue(record.value);
    updateSchema([
      {
        field: 'loginCode',
        componentProps: {
          disabled: op.value === 'auth',
        },
      },
      {
        field: 'userName',
        componentProps: {
          disabled: op.value === 'auth',
        },
      },
    ]);
    if (op.value === 'add' || op.value === 'auth') {
      setUserRoleTableData(res);
    }
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        userCode: record.value.userCode,
        op: op.value,
      };
      data.userType = 'teacher';
      data.userName = data.vteacher.teacherName;
      if (op.value == 'edit' || op.value == 'auth') {
        data.userCode = record.value.userCode;
        data.vteacher.teacherId = record.value.vteacher.teacherId;
      }
      if (op.value === 'add' || op.value === 'edit') {
        console.log(avatar.value);
        data.teacherUser_avatar = avatar.value.id;
        data.vteacher.headPortrait = avatar.value.fileUrl;
        //   // if (!data.employee.empNo) {
        //   //   data.employee.empNo = record.value.loginCode;
        //   // }
        //   // data.employee.employeeOfficeList = await getEmployeeOfficeList();
      }
      if (op.value === 'add' || op.value === 'auth') {
        data.userRoleString = userRoleTable.getSelectRowKeys().join(',');
      }
      // console.log('submit', params, data, record);
      const res = await teacherUserSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
